import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 布局组件
import home from '../layout/index.vue'
import LRLayout from '@/layout/LRLayout.vue'

// 视图组件
import ShowView from '@/views/showView.vue'
import Notices from '../views/NoticeList.vue'
import Login from '@/views/Login.vue'
import RegisterVue from '@/views/RegisterVue.vue'
import Forget from '@/views/Forget.vue'
import Menu from '@/views/Menu.vue'
import Home from '@/views/front/Home.vue'

const routes = [
  {
    path: "/login",
    name: "LRLayout",
    redirect: '/login',
    component: LRLayout,
    children: [
      {
        path: "/login",
        name: "Login",
        component: Login,
      },
      {
        path: "/register",
        name: "Register",
        component: RegisterVue
      },
      {
        path: '/forget',
        name: 'Forget',
        component: Forget
      }
    ]
  },
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404.vue')
  },
  {
    path: '/products',
    name: 'Products',
    component: () => import('@/views/front/Products.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('@/views/front/Cart.vue')
  },
  {
    path: '/favorite',
    name: 'Favorite',
    component: () => import('@/views/front/Favorite.vue'),
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/category/:id',
    name: 'category',
    component: () => import('@/views/front/Category.vue')
  },
  {
    path: '/message1',
    name: 'MessageManager',
    component: () => import('@/views/front/MessageManager.vue')
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import('@/views/front/Order.vue')
  },
  {
    path: '/user-center',
    name: 'UserCenter',
    component: () => import('@/views/front/UserCenter.vue'),
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('@/views/front/ProductDetail.vue')
  },
  {
    path: '/seckill',
    name: 'Seckill',
    component: () => import('@/views/front/SeckillList.vue')
  },
  {
    path: '/seckill/:id',
    name: 'SeckillDetail',
    component: () => import('@/views/front/SeckillDetail.vue')
  },
  {
    path: '/articles',
    name: 'Articles',
    component: () => import('@/views/front/Article.vue')
  },
  {
    path: '/article/:id',
    name: 'ArticleDetail',
    component: () => import('@/views/front/ArticleDetail.vue')
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('@/views/front/Search.vue'),
    meta: {
      title: '搜索结果'
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 动态添加路由的函数
export const setRoutes = () => {
  const userMenuListStr = localStorage.getItem("userMenuList")
  if (userMenuListStr && userMenuListStr !== 'undefined') {
    // 检查路由是否已存在
    const hasLayoutRoute = router.hasRoute('home')
    if (!hasLayoutRoute) {
      const currRouter = {
        path: '/',
        name: 'home',
        component: home,
        redirect: '/showView',
        children: [
          {
            path: "/showView",
            name: "homeView",
            component: ShowView,
            meta: {
              title: "首页"
            },
          },
          {
            path: '/menu',
            name: 'Menu',
            component: Menu,
            meta: {
              title: "菜单管理"
            },
          },
        ]
      }

      try {
        const menus = JSON.parse(userMenuListStr);
        menus.forEach((item) => {
          if (item.path) {
            const itemMenu = {
              path: item.path.replace("/", ""),
              name: item.name,
              component: () => import(`../views/${item.pagePath}.vue`),
              meta: {
                title: item.name
              }
            };
            currRouter.children?.push(itemMenu);
          } else if (item.children?.length) {
            item.children.forEach((childItem) => {
              if (childItem.path) {
                const itemMenu = {
                  path: childItem.path.replace("/", ""),
                  name: childItem.name,
                  component: () => import(`../views/${childItem.pagePath}.vue`),
                  meta: {
                    title: childItem.name
                  }
                };
                currRouter.children?.push(itemMenu);
              }
            });
          }
        });
        router.addRoute(currRouter)
      } catch (err) {
        console.error('Failed to parse userMenuList:', err);
      }
    }
  }
}

// 初始化路由
setRoutes()

// 处理路由错误
router.onError((error) => {
  if (error.message.includes('Cannot find module')) {
    router.replace('/404');
  }
})

// 路由守卫
router.beforeEach((to, from) => {
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const userInfo = localStorage.getItem('frontUser')
    if (!userInfo) {
      ElMessage({
        message: '请先登录',
        type: 'warning'
      })
      return '/login'
    }
  }

  // 记录当前路径名称
  if (to.name) {
    localStorage.setItem('currentPathName', to.name.toString());
  }

  // 处理404情况
  const localMenus = localStorage.getItem("userMenuList");
  if (to.matched.length === 0) {
    if (to.path !== '/404') {
      if (localMenus) {
        // 跳转到404并记录来源
        return {
          path: '/404',
          query: { redirect: from.fullPath }
        }
      } else {
        ElMessage({
          message: '请先登录',
          type: 'warning'
        });
        return '/login'
      }
    }
  }

  // 正常导航
  return true
})

// 修复路由重复导航的问题
const originalPush = router.push
router.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

export default router
